"""
数据库连接和会话管理
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from contextlib import contextmanager
from typing import Generator
import os

from .config import get_settings

# 获取配置
settings = get_settings()

# 创建数据库引擎
engine = create_engine(
    settings.database_url,
    connect_args={"check_same_thread": False} if "sqlite" in settings.database_url else {}
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 基础模型类
from models.base import Base


def get_db() -> Generator[Session, None, None]:
    """获取数据库会话"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@contextmanager
def get_db_context():
    """获取数据库会话上下文管理器"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def create_tables():
    """创建所有数据库表"""
    # 确保所有模型都被导入
    from models.database import User, SystemConfig, ParseTask, ParseResult, SliceTask, SliceChunk, APILog, TokenBlacklist
    Base.metadata.create_all(bind=engine)


def drop_tables():
    """删除所有数据库表"""
    from .database import Base
    Base.metadata.drop_all(bind=engine)


def init_db():
    """初始化数据库"""
    create_tables()
    
    # 创建默认管理员用户
    from models.database import User
    from .auth import get_password_hash
    
    db = SessionLocal()
    try:
        # 检查是否已存在管理员用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        if not admin_user:
            admin_user = User(
                username="admin",
                email="admin@system.com",
                password_hash=get_password_hash("admin123"),
                role="admin"
            )
            db.add(admin_user)
            db.commit()
            print("默认管理员用户已创建：admin/admin123")
    finally:
        db.close()


if __name__ == "__main__":
    init_db()